import {DecryUtil} from 'jy-http-dense';
import store from "../store";
import utils from "./utils";
const baseUrl = ()=>{
    return `${store.getters.vuex_env_conf?.API_BASE_URL}/`;
};

const defaultHttpConfig = {
    header: {
        'content-type': 'application/json',
        'app': 'android'
    },
    method: "POST",
    timeout:8000,
    dataType: "json",
    success() {},
    fail() {},
    complete() {}
}
const apiPost = (url, data = {},showLoading=true, myBaseUrl=baseUrl()) => {
    if(url.indexOf("/") == 0 && url.split("/").length>2){
        url = url.replace("/","");
    }
    showLoading && utils.showLoading();
    return new Promise((resolve,reject) => {
        const sTime = new Date().getTime();
        let {res, error} = {};
        let requestTime = (data.requestTime || new Date().getTime())+"";
        if(store.state.token){
            defaultHttpConfig.header['appsid'] = store.state.token;
        } else {
            delete defaultHttpConfig.header['appsid'];
        }
        defaultHttpConfig.header['app'] = store.state.platform;
        defaultHttpConfig.header['devicetype'] = store.state.platform;
        // data.device = store.state.deviceId;
        uni.request(Object.assign({},defaultHttpConfig,{
            url:myBaseUrl + url,
            data: DecryUtil.e(data, url, requestTime),
            complete: (response) => {

                if (response.statusCode == 200 && response.data) {
                    try{
                        let rData = DecryUtil.d(requestTime, response.data);
                        console.log(rData)
                        if (rData && rData.rtnStatus == 0) {
                            res = rData.data;
                        } else if([-2,-3,'-2','-3'].includes(rData.rtnStatus)){
                            store.commit("logout");
                            return reject();
                        } else {
                            let er = rData;
                            if(er){
                                if(er?.rtnStatus){

                                } else {
                                    er = {rtnStatus:"F00000",rtnMsg:"网关异常"};
                                }
                            } else {
                                er = {rtnStatus:"F00001",rtnMsg:"无数据"};
                            }

                            error = er;
                        }
                    }catch (e) {
                        console.error(e);
                        error = {rtnStatus:"F00001",rtnMsg:"数据异常"};
                    }
                } else {
                    error = {rtnStatus:"F00002",rtnMsg:"服务异常"};
                }
                try{
                    console.log(`${url}:${new Date().getTime()-sTime}`);
                    // console.log(JSON.stringify({data,res,error}));
                    console.log({data,res,error});
                    console.log(res)
                }catch (e){

                }
                resolve({res, error});
            }
        }));
    }).finally((e)=>{
        showLoading && uni.hideLoading();
    });
}

const apiPostMd5 = (url, data = {},showLoading=true, myBaseUrl=baseUrl()) => {
    return apiPost(DecryUtil.urlMd5(url), data,showLoading, myBaseUrl);
}

const uploadFile = (tempFilePaths)=>{
    return new Promise((resolve => {
        uni.uploadFile({
            url: `${store.getters.vuex_env_conf?.FILE_BASE_URL}`,
            filePath: tempFilePaths,
            name:"file",
            success(ress) {
                if(ress?.statusCode == 200 && ress?.data){
                    try{
                        ress.data = JSON.parse(ress?.data)
                    }catch (e){

                    }
                }
                resolve(ress?.data?.data)
            },
            fail() {
                resolve();
            }
        })
    }));

}

const downloadFile = (url,success,onProgressUpdate)=>{
    let downloadTask = uni.downloadFile({
        url: url,
        success: res => {
            if (res.statusCode == 200) {
                success(res.tempFilePath)
            } else {
                success()
            }
        },
        fail:(e)=>{
            success("error",e)
        },
        complete: () => {
        }
    });

    downloadTask.onProgressUpdate(res => {
        onProgressUpdate && onProgressUpdate(res.progress,(res.totalBytesWritten / Math.pow(1024, 2)).toFixed(2),(res.totalBytesExpectedToWrite / Math.pow(1024, 2)).toFixed(2));
    });
    return downloadTask;
}

export default {
    apiPost,apiPostMd5,uploadFile,downloadFile
};
